//
//  BrideSayViewController.m
//  TrueLove
//
//  Created by han on 15-1-28.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "BrideSayViewController.h"
#import "MyGroupCell.h"
#import "StoryViewController.h"
#import "GroupViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "Bride.h"
@interface BrideSayViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UIPageControl *pageControl;

@end

@implementation BrideSayViewController

- (void)dealloc
{
    [_tableView release];
    [_scrollView release];
    [_arrGroup release];
    [_arrPic release];
    [_flakeImage release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self netWorkingRequestForGroup];
    [self netWorkingRequestForScrollPicture];
    [self createSegmentedControl];

    //自动跳页
    [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
    //添加动画
    self.flakeImage = [UIImage imageNamed:@"iconfont-duihuaqipao5.png"];
    [NSTimer scheduledTimerWithTimeInterval:(0.2) target:self selector:@selector(play) userInfo:nil repeats:YES];
    
}

//动画
- (void)play {
    UIImageView *flakeView = [[UIImageView alloc] initWithImage:self.flakeImage];
    int startX = round(random() % 1024);
    int endX = round(random() % 1024);
    double scale = 1 / round(random() % 100) + 1.0;
    double speed = 1 / round(random() % 100) + 1.0;
    flakeView.frame = CGRectMake(startX, -100.0, 25.0 * scale, 25.0 * scale);
    flakeView.alpha = 0.55;
    [self.view addSubview:flakeView];
    [UIView beginAnimations:nil context:flakeView];
    [UIView setAnimationDuration:10 * speed];
    flakeView.frame = CGRectMake(endX, 768.0, 25.0 * scale, 25.0 * scale);
    [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    UIImageView *flakeView = context;
    [flakeView removeFromSuperview];
    [flakeView release];
}



// 小组信息的网络请求
- (void)netWorkingRequestForGroup
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:@"http://www.hunliji.com/v1/api/app/community/groups?sort=id" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
        NSArray *arr = [dic objectForKey:@"groups"];
        self.arrGroup = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Bride *bride = [[Bride alloc] init];
            [bride setValuesForKeysWithDictionary:dic];
            [self.arrGroup addObject:bride];
            [bride release];
        }
        [_tableView reloadData];
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@",error);
    }];

}

//轮播照片网络请求
- (void)netWorkingRequestForScrollPicture
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:@"http://www.hunliji.com/v2/api/app/banners.json?site=6" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.arrPic = [NSMutableArray array];
        self.arrPic = [NSMutableArray arrayWithArray:responseObject];
        [self createTableView];
        [self createPageControl];
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@",error);
    }];
}

//创建segmentControl
- (void)createSegmentedControl
{
    NSArray *arr = [NSArray arrayWithObjects:@"小组",@"故事", nil];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:arr];
    self.navigationItem.titleView = segment;
    segment.tintColor = [UIColor redColor];
    segment.selectedSegmentIndex = 0;//给一个默认选中的段
    [segment addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
}

//segment关联的方法
- (void)controllerPressed:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 1) {
        StoryViewController *storyVC = [[StoryViewController alloc] init];
        [self.navigationController pushViewController:storyVC animated:NO];
        [storyVC release];
    }
    //pop回来的视图不刷新,所以要提前设定
    segment.selectedSegmentIndex = 0;
    
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    //关闭透明度
    self.navigationController.navigationBar.translucent = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self createScrollViewWithImageView];

    self.tableView.tableHeaderView = self.scrollView;
    [self.view addSubview:_tableView];
    [_tableView release];
    
}
//上面的轮播照片
- (void)createScrollViewWithImageView
{
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;//按页滑动
    //隐藏滚动条
    [self.scrollView setShowsHorizontalScrollIndicator:NO];
    
    [self handleImage];
    
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * self.arrPic.count, 0);
    for (NSInteger i = 0; i < self.arrPic.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(self.scrollView.frame.size.width * i, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
        [imageView setImageWithURL:[NSURL URLWithString:[[self.arrPic objectAtIndex:i] objectForKey:@"image_path"]]];
        [_scrollView addSubview:imageView];
        [imageView release];
    }
    [self.view addSubview:_scrollView];
    [_scrollView release];
}

//在照片数组中 前后各方一张 最后一张照片的地址  和 第一张的地址
- (void)handleImage
{
    id firsrImage = [self.arrPic lastObject];
    id lastImage = [self.arrPic firstObject];
    [self.arrPic insertObject:firsrImage atIndex:0];
    [self.arrPic addObject:lastImage];
}

// 添加pageControl
- (void)createPageControl
{
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width / 2 - 40,self.scrollView.frame.size.height - 30 ,80 , 30)];
    self.pageControl.numberOfPages = [self.arrPic count] - 2;//减去前后添加的两张照片
    [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    self.pageControl.pageIndicatorTintColor = [UIColor blackColor];
    [self.tableView addSubview:self.pageControl];
    [_pageControl release];
    
}

// 添加点击pageControl的方法
- (void)changePage:(UIPageControl *)page
{
    [self.scrollView setContentOffset:CGPointMake((page.currentPage + 1) * self.scrollView.frame.size.width, 0) animated:NO];
    
}

// 实现循环滚动
// 减速结束时
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x >= self.scrollView.frame.size.width * (self.arrPic.count - 1)) {
        
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width, 0) animated:NO];
    }
    if (self.scrollView.contentOffset.x <= 0) {
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * (self.arrPic.count - 2), 0)  animated:NO];
    }
}

// 使页面的变化和pageControl变化一致
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int half = self.scrollView.frame.size.width / 2;
    self.pageControl.currentPage = (self.scrollView.contentOffset.x - self.scrollView.frame.size.width - half) / (self.scrollView.frame.size.width) + 1;
}

//自动播放的方法
- (void)runTimePage
{
    NSInteger page = self.pageControl.currentPage;
    page++;
    page = page > self.arrPic.count - 3 ? 0 : page;
    self.pageControl.currentPage = page;
    [self changePage:self.pageControl];
//    NSLog(@"%ld",page);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrGroup.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *str = @"reuse";
    MyGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[MyGroupCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }
    //取消选中的状态效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        Bride *bride = [self.arrGroup objectAtIndex:indexPath.row];
        [cell.MyImageView setImageWithURL:[NSURL URLWithString:bride.image]];
        cell.titleLabel.text = bride.title;
        cell.descriptionLabel.text = bride.MyDescription;
        cell.todayLabel.text = [NSString stringWithFormat:@"今日%@",[bride.added_threads_count stringValue]];
        cell.browseLabel.text = [[bride.click_count stringValue] stringByAppendingString:@"浏览"];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupViewController *groupVC = [[GroupViewController alloc] init];
    //属性传值到详情界面
    groupVC.groupBride = [self.arrGroup objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:groupVC animated:YES];
    [groupVC release];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
